<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/8/9
 * Time: 13:59
 */

namespace app\web\controller;

use \think\Controller;
use \think\Env;
use \app\common\lib\Jssdk;

/**
 * Wap页面用到的接口
 * Class Wap
 * @package app\web\controller
 */
class Wap extends Controller
{
    //微信分享图片
    protected $share_img = '';

    public function _initialize()
    {

    }

    /**
     * wap 微信登录
     * @return \think\response\Json
     */
    public function wechat_login()
    {
        $callback_url = input('callback_url');

        //检查session，如果不存在，那么就直接跳转到登录
        $this->checkLogin();

        $user_info = [
            'nickname' => session('love.nickname'),
            'sex' => session('love.sex'),
            'city' => session('love.city') == '' ? '' : session('love.city'),
            'province' => session('love.province') == '' ? '' : session('love.province'),
            'country' => session('love.country'),
            'headimgurl' => session('love.headimgurl'),
            'openid' => session('love.openid'),
            'unionid' => session('love.unionid'),
        ];

        if (
            !isset($user_info['nickname'])
            || !isset($user_info['sex'])
            || !isset($user_info['city'])
            || !isset($user_info['province'])
            || !isset($user_info['country'])
            || !isset($user_info['headimgurl'])
            || !isset($user_info['openid'])
            || !isset($user_info['unionid'])
        )
        {
            return show(config('code.error'), '用户信息错误', $user_info);
        }

        try
        {
            $wap_domain = Env::get('host.wap_domain');
//            header('location:' . $wap_domain . '/#/pages/login/index?user_info=' . json_encode($user_info));
            if (!isset($callback_url))
            {
                header('location:' . $wap_domain . '/#/pages/login/index?user_info=' . json_encode($user_info));
            } else
            {
                header('location:' . urldecode($callback_url) . json_encode($user_info));
            }
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), $e->getMessage());
        }
    }

    /**
     * 获取微信签名
     * @return \think\response\Json
     */
    public function wechat_get_sign()
    {
        $url = input('url');

        if (!isset($url))
        {
            return show(config('code.error'), 'url参数错误！');
        }

        try
        {
            $signPackage = (new Jssdk())->getSignPackage($url);
            return show(config('code.success'), '获取成功', $signPackage);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), $e->getMessage());
        }
    }


    /**
     * 微信登陆
     */
    public function weixin_login()
    {
        $token = '123';
        $appid = config('wechat.mp_appid');
        $domain = Env::get('host.domain');
        $redirect_uri = urlencode($domain . '/web/wap/weixin_back');
        header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . $token . '#wechat_redirect');
        exit;
    }

    /**
     * 微信登陆返回
     */
    public function weixin_back()
    {
        $appid = config('wechat.mp_appid');
        $appsecret = config('wechat.mp_secret');

        $code = input('get.code');
        if (empty($code)) $this->error('微信授权失败！');

        $token = input('get.state');
        if (empty($token)) $this->error('获取token失败！');
        if (empty(session('love.access_token')))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
            $access_token = json_decode(file_get_contents($access_token_url));
            if (isset($access_token->errcode))
            {
                $this->error('授权失败');
            }
            session('love.access_token', $access_token->access_token);
            session('love.refresh_token', $access_token->refresh_token);
            session('love.openid', $access_token->openid);
        }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . session('love.access_token') . '&openid=' . session('love.openid') . '&lang=zh_CN';
        $user_info = json_decode(file_get_contents($user_info_url));
        if (isset($user_info->errcode))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . session('love.refresh_token');
            $access_token = json_decode(file_get_contents($access_token_url), true);
            if (!empty($access_token) && isset($access_token['access_token']) && isset($access_token['refresh_token']) && isset($access_token['openid']))
            {
                session('love.access_token', $access_token['access_token']);
                session('love.refresh_token', $access_token['refresh_token']);
                session('love.openid', $access_token['openid']);

                $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token['access_token'] . '&openid=' . $access_token['openid'] . '&lang=zh_CN';
                $user_info = json_decode(file_get_contents($user_info_url));
                if (isset($user_info->errcode))
                {
                    echo '<h1>错误：</h1>' . $user_info->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
                    exit;
                }
            } else
            {//失败的话，重新授权登录
                $this->redirect('/web/wap/weixin_login');
            }
        }
        //把微信返回的参数 保存到session里
        session('love.nickname', $user_info->nickname);
        session('love.sex', $user_info->sex);
        session('love.city', $user_info->city);
        session('love.province', $user_info->province);
        session('love.country', $user_info->country);
        session('love.headimgurl', $user_info->headimgurl);
        session('love.unionid', $user_info->unionid);

        $this->redirect('/web/wap/wechat_login');
    }


    /**
     * 检查session里是否有  unionid、headimgurl、name 这三个参数，如果为空，那么跳转到微信登录页面
     * @param $token
     */
    private function checkLogin()
    {
        if (empty(session('love.unionid')) || empty(session('love.headimgurl')) || empty(session('love.nickname')))
        {
            $this->redirect('/web/wap/weixin_login');
        }
    }

}
